<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>枚举一个对象的所有属性</title>
    </head>
    <body>
        <div>
            <a
                href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in"
            >
                for...in</a
            >以任意顺序遍历一个对象的除Symbol以外的可枚举属性。
        </div>
        <script>
            class Parent {
                constructor(name) {
                    this.name = name;
                    this.height = name;
                }
                say() {}
            }
            class Child extends Parent {
                constructor(name, age) {
                    super(name);
                    this.age = age;
                }
                say() {}
            }
            Child.prototype.sex = "1";
            const child = new Child("child", 10);
            console.log(child);
        </script>
        <script>
            <!-- ES6之前 -->
            function listAllProperties(o, isEnumerable = false) {
                //获取所有属性，包含原型链
                let objectToInspect;
                let result = [];
                for (
                    objectToInspect = o;
                    objectToInspect !== null;
                    objectToInspect = Object.getPrototypeOf(objectToInspect)
                ) {
                    result = result.concat(
                        Object.getOwnPropertyNames(objectToInspect)
                    );
                }
                //数组元素去重
                const newRes = [];
                result.forEach((item) => {
                    if (newRes.indexOf(item) === -1) {
                        if (isEnumerable === true) {
                            //保留不可枚举属性
                            newRes.push(item);
                        } else {
                            //不保留不可枚举属性
                            o.propertyIsEnumerable(item) && newRes.push(item);
                        }
                    }
                });
                return newRes;
            }

            console.log("ES5之前:", listAllProperties(child, true));
        </script>
        <script>
            const keys = [];
            for (let key in child) {
                keys.push(key);
            }
            console.log("for...in:", keys);
            console.log("Object.keys:", Object.keys(child));
            console.log(
                "Object.getOwnPropertyNames:",
                Object.getOwnPropertyNames(child)
            );
        </script>
    </body>
</html>
<script>
    console.log(
        "Object.getOwnPropertyNames:",
        Object.getOwnPropertyNames(child)
    );
</script>
